<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>闭包选项卡</title>
</head>

<body>
    <ul>
        <li class="active-li">1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <div class="active-div">1</div>
    <div>2</div>
    <div>3</div>
    <script>
        // 闭包可以保存信息
        const li = document.querySelectorAll('li')
        const box = document.querySelectorAll('div')
        var clearClass = () => {
            for (var j = 0; j < li.length; j++) {
                li[j].className = ''
                box[j].className = ''
            }
        }
        for (var i = 0; i < li.length; i++) {
            // 闭包方法 n是私有作用域的变量 储存起来了 自执行函数 执行完毕不销毁
            // ~function (n) {
            //     li[i].onclick = function () {
            //         clearClass()
            //         li[n].className = 'active-li'
            //         box[n].className = 'active-div'
            //     }
            // }(i)
            li[i].onclick = ~function (n) {
                return function () {
                    clearClass()
                    console.log(n);
                    li[n].className = 'active-li'
                    box[n].className = 'active-div'
                }
            }(i)
            //     li[i].idx = i
            //     li[i].onclick = function () {
            //         clearClass()
            //         this.className = 'active-li'
            //         box[this.idx].className = 'active-div'
            //     }
        }

    </script>
</body>
<style>
    * {
        padding: 0;
        margin: 0;
    }

    ul {
        height: 50px;
    }

    li {
        float: left;
        width: 80px;
        height: 50px;
        border: 1px solid #000;
        list-style: none;
    }

    div {
        width: 200px;
        height: 120px;
        border: 1px solid #000;
        display: none;
    }

    .active-li {
        background-color: aquamarine;
    }

    .active-div {
        display: block;
    }
</style>

</html>